<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, nextTick } from 'vue'
import * as mars3d from 'mars3d'

let map: mars3d.Map | null = null
const containerRef = ref<HTMLDivElement | null>(null)

onMounted(async () => {
  await nextTick()
  if (!containerRef.value) return
  
  // 🔑 天地图 Key 配置（需要自行申请：https://console.tianditu.gov.cn/）
  const tdtKey = (window as any).TDTTOKEN || localStorage.getItem('tdtTk') || ''
  
  // 🗺️ 配置多种底图选项
  const basemaps: any[] = []
  
  // 如果有天地图 Key，添加天地图底图
  if (tdtKey) {
    basemaps.push(
      { name: '天地图影像', type: 'tdt', layer: 'img_d', key: tdtKey, show: true },
      { name: '天地图注记', type: 'tdt', layer: 'cia_d', key: tdtKey }
    )
  } else {
    // 没有天地图 Key 时，使用 Cesium 自带的底图
    basemaps.push(
      {
        name: 'ArcGIS 影像',
        type: 'arcgis',
        url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
        show: true
      },
      {
        name: 'ArcGIS 注记',
        type: 'arcgis',
        url: 'https://services.arcgisonline.com/ArcGIS/rest/services/Reference/World_Boundaries_and_Places/MapServer'
      }
    )
    console.warn('⚠️ 未配置天地图 Key，已切换到 ArcGIS 底图。如需使用天地图，请访问 https://console.tianditu.gov.cn/ 申请 Key')
  }
  
  map = new mars3d.Map(containerRef.value as any, {
    scene: {
      center: { lat: 31.8407, lng: 117.251, alt: 2000000, heading: 0, pitch: -60 },
    },
    basemaps,
    // 🏔️ 启用地形（示例服务，可更换为自有地形服务）
    // 🚀 Electron 环境需要使用完整的 http/https 协议
    terrain: { url: 'http://data.mars3d.cn/terrain', show: true, requestVertexNormals: true, requestWaterMask: true }
  })

  // 开启地形深度测试，增强与地形的遮挡与贴地效果
  try { (map as any).scene.globe.depthTestAgainstTerrain = true } catch {}

  // 暴露全局 map 与图层，便于导入/编辑
  // @ts-ignore
  window.map = map
  // @ts-ignore
  window.graphicLayer = new mars3d.layer.GraphicLayer()
  // @ts-ignore
  window.QFDLayer = new mars3d.layer.GraphicLayer()
  // @ts-ignore
  window.graphicLayer.addTo(map)
  // @ts-ignore
  window.QFDLayer.addTo(map)
})

onBeforeUnmount(() => {
  map?.destroy()
  map = null
})
</script>

<template>
  <div ref="containerRef" class="mars3d-container"></div>
</template>

<style scoped>
.mars3d-container {
  position: absolute;
  inset: 0;
}
</style>


